import React, { useRef, useState } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Popconfirm, Tag, Space } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, RobotOutlined, CustomerServiceOutlined, BarChartOutlined, CodeOutlined, SearchOutlined, BookOutlined, GlobalOutlined, BulbOutlined, AimOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import api from '../../services/api';
import { Agent } from '../../types';

const AgentList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const fetchAgents = async (params: any) => {
    try {
      const response = await api.get('/agents/', {
        params: {
          skip: (params.current - 1) * params.pageSize,
          limit: params.pageSize,
        },
      });
      
      // 后端返回的是数组或分页对象
      const data = response.data;
      const agents = Array.isArray(data) ? data : (data.items || []);
      const total = data.total !== undefined ? data.total : agents.length;
      
      // 转换字段名称：后端返回 camelCase，前端期望 snake_case
      const transformedData = agents.map((agent: any) => ({
        ...agent,
        ve_admins: agent.adminUserIds || agent.ve_admins || [],
        team_access: agent.teamAccessIds || agent.team_access || [],
        knowledge_bases: agent.knowledgeBaseIds || agent.knowledge_bases || [],
        plugins: agent.pluginIds || agent.plugins || [],
        system_prompt: agent.systemMetaPrompt || agent.system_prompt,
        model_name: agent.modelVersion || agent.model_name,
        created_at: agent.createdAt || agent.created_at,
        updated_at: agent.updatedAt || agent.updated_at,
      }));
      
      return {
        data: transformedData,
        success: true,
        total: total,
      };
    } catch (error: any) {
      message.error('Failed to fetch agents');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const handleDelete = async (id: number) => {
    setLoading(true);
    try {
      await api.delete(`/agents/${id}`);
      message.success('Agent deleted successfully');
      actionRef.current?.reload();
    } catch (error: any) {
      message.error(error.response?.data?.detail || 'Failed to delete agent');
    } finally {
      setLoading(false);
    }
  };

  const getIconComponent = (iconName?: string) => {
    const iconMap: Record<string, any> = {
      'RobotOutlined': <RobotOutlined />,
      'CustomerServiceOutlined': <CustomerServiceOutlined />,
      'BarChartOutlined': <BarChartOutlined />,
      'CodeOutlined': <CodeOutlined />,
      'SearchOutlined': <SearchOutlined />,
      'BookOutlined': <BookOutlined />,
      'GlobalOutlined': <GlobalOutlined />,
      'BulbOutlined': <BulbOutlined />,
      'AimOutlined': <AimOutlined />,
    };
    return iconMap[iconName || 'RobotOutlined'] || <RobotOutlined />;
  };

  const columns: ProColumns<Agent>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: 'Name',
      dataIndex: 'name',
      copyable: true,
      render: (_, record) => (
        <Space>
          {getIconComponent(record.icon)}
          {record.name}
        </Space>
      ),
    },
    {
      title: 'Category',
      dataIndex: 'category',
      render: (_, record) => record.category ? (
        <Tag color="blue">{record.category}</Tag>
      ) : null,
      valueEnum: {
        'Customer Service': { text: 'Customer Service' },
        'Data Analysis': { text: 'Data Analysis' },
        'Code Assistant': { text: 'Code Assistant' },
        'Content Creation': { text: 'Content Creation' },
        'Research': { text: 'Research' },
        'Translation': { text: 'Translation' },
        'Other': { text: 'Other' },
      },
    },
    {
      title: 'Description',
      dataIndex: 'description',
      search: false,
      ellipsis: true,
    },
    {
      title: 'Model Provider',
      dataIndex: 'model_provider',
      search: false,
    },
    {
      title: 'Model Name',
      dataIndex: 'model_name',
      search: false,
    },
    {
      title: 'Admins',
      dataIndex: 've_admins',
      search: false,
      render: (_, record) => record.ve_admins.length,
    },
    {
      title: 'Team Access',
      dataIndex: 'team_access',
      search: false,
      render: (_, record) => record.team_access.length,
    },
    {
      title: 'Knowledge Bases',
      dataIndex: 'knowledge_bases',
      search: false,
      render: (_, record) => record.knowledge_bases.length,
    },
    {
      title: 'Plugins',
      dataIndex: 'plugins',
      search: false,
      render: (_, record) => record.plugins.length,
    },
    {
      title: 'Created At',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: 'Action',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button
          key="edit"
          type="link"
          icon={<EditOutlined />}
          onClick={() => navigate(`/agents/edit/${record.id}`)}
        >
          Edit
        </Button>,
        <Popconfirm
          key="delete"
          title="Are you sure to delete this agent?"
          onConfirm={() => handleDelete(record.id)}
          okText="Yes"
          cancelText="No"
        >
          <Button type="link" danger icon={<DeleteOutlined />} loading={loading}>
            Delete
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ProTable<Agent>
      columns={columns}
      actionRef={actionRef}
      request={fetchAgents}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      pagination={{
        defaultPageSize: 10,
        showSizeChanger: true,
      }}
      dateFormatter="string"
      headerTitle="Agent Management"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => navigate('/agents/create')}
          type="primary"
        >
          Create Agent
        </Button>,
      ]}
    />
  );
};

export default AgentList;
